package logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import org.json.JSONArray;
import org.json.JSONObject;





/**
 * Create, Read, (no update and delete) books. 
 * @author Guilherme
 *
 */
public class CRUDBooks {	
	
	public static String USERPATH = new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
	public static String SEPARATOR = System.getProperty("file.separator");
	public static String COOLRENT_FOLDER = USERPATH + SEPARATOR + "coolrent";
	public static String BOOKS_FILE = COOLRENT_FOLDER + SEPARATOR + "books.data";
	
	private ArrayList<Book> books;
	
	public CRUDBooks() throws FileNotFoundException, ClassNotFoundException, IOException {
		books = loadBooks();
	}
	
	
	
	/**
	 * Persiste um novo livro no banco de dados caso ele não exista.
	 * @param owner
	 * @param holder
	 * @param title
	 * @param author
	 * @param isbn
	 * @param available
	 * @throws Exception Livro já cadastrado por outro usuário.
	 */
	public void addBook(User owner, User holder, String title, String author, String isbn, boolean available ) throws Exception {
		Book b = new Book(owner, holder, title, author, isbn, available);
		if (!books.contains(b)){
			books.add(b);
			updateBooksFile();
		} else { 
			throw new Exception("Livro adicionado");
		}
		
	}
	
	
	public ArrayList<Book> getBooks() {
		return books;
	}
	
	/**
	 * Salva mudanças feitas na lista de livros. 
	 */
	private void updateBooksFile() {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(BOOKS_FILE));
			oos.writeObject(books);
			oos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private ArrayList<Book> loadBooks() throws FileNotFoundException,
			IOException, ClassNotFoundException {

		File booksFile = new File(BOOKS_FILE);
		ArrayList<Book> op;
		if (booksFile.exists()) {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
					booksFile));
			op = (ArrayList<Book>) ois.readObject();
			return op;
		} else {
			booksFile.createNewFile();
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(booksFile));
			op = new ArrayList<Book>();
			oos.writeObject(op);
		}
		
		return op;		
	}
	
	public static String[] searchBookByISBN(String isbn) throws Exception{
		isValidISBN(isbn);
		URLConnection con = new URL("http://isbndb.com/api/v2/json/XRN25R26/book/" + isbn).openConnection();
		BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
		
		StringBuilder xmlContent = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null){
			xmlContent.append(line + "\n");
		}
		
		org.json.JSONObject jo = new org.json.JSONObject(xmlContent.toString());	
		JSONObject dataObj = (JSONObject) jo.getJSONArray("data").get(0);
		JSONObject authorObj = (JSONObject) dataObj.getJSONArray("author_data").get(0);

		String bookTitle = (String) dataObj.get("title");
		String authorName = (String) authorObj.get("name");
		
		return new String[] {bookTitle, authorName, isbn};
	}



	private static boolean isValidISBN(String isbn) throws Exception {
		if (isbn.length() == 13 || isbn.length() == 10){
			return true;
		}
		throw new Exception("ISBN inválido! Use somente numeros sem espaços e caracteres especiais");
		
	}
	
	public ArrayList<Book> searchBookByAuthor(String author){
		
		ArrayList<Book> result = new ArrayList<>();
		
		for (int i = 0; i < getBooks().size(); i++) {
			
			if (getBooks().get(i).getAuthor().equals(author))
				result.add(getBooks().get(i));
		}
		
		return result;
		
	}
	
	
	
	
	// Por falta de alguém pra testar :( 
/*	public static void main(String[] args)  {
		try {
			CRUDBooks cb = new CRUDBooks(); 
			User u = CRUDUsers.getUser("guilheremsteinmuller@gmail.com");
			cb.addBook(u, u, "Software Engineering", "Ian Sommerville", "0201427656", true);
			System.out.println("livro adicionado.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Erro : " + e.getMessage());
		}
	}*/

}
